import 'package:flutter/material.dart';

import '../table.dart';

/// 可拆分的单元格绘制器
abstract class KqBaseSplitCellRender extends CellRender {
  /// 获取被拆分单元格数据
  SplitCell? getSplitCell(int row, int column);

  @override
  Widget build(BuildContext context, int row, int column, double width,
      double height, bool isLongPress) {
    var splitCell = getSplitCell(row, column);
    if (splitCell == null) {
      return SizedBox(width: width, height: height);
    }

    var childrenCell = splitCell.children;
    Widget result;
    if (childrenCell == null || childrenCell.isEmpty) {
      result = buildChildCell(context, row, column, isLongPress, splitCell);
    } else {
      result = _buildChildren(context, row, column, isLongPress, splitCell,
          childrenCell, splitCell.axis);
    }
    result =  SizedBox(width: width, height: height, child: result);
    return result;
  }

  Widget _buildChildCell(BuildContext context, int row, int column,
      bool isLongPress, SplitCell cell) {
    var childrenCell = cell.children;
    Widget result;
    if (childrenCell == null || childrenCell.isEmpty) {
      result = buildChildCell(context, row, column, isLongPress, cell);
    } else {
      result = _buildChildren(
          context, row, column, isLongPress, cell, childrenCell, cell.axis);
    }
    if (cell.flex != null) {
      result = Expanded(flex: cell.flex!, child: result);
    }
    return result;
  }

  Widget _buildChildren(
      BuildContext context,
      int row,
      int column,
      bool isLongPress,
      SplitCell cell,
      List<SplitCell> childrenCell,
      Axis axis) {
    List<Widget> childWidgets = [];
    for (var childCell in childrenCell) {
      var result =
          _buildChildCell(context, row, column, isLongPress, childCell);
      childWidgets.add(result);
    }

    if (axis == Axis.horizontal) {
      return Row(children: childWidgets);
    } else {
      return Column(children: childWidgets);
    }
  }

  /// 构建子单元格内容
  /// [row]、[column]为被拆分单元格[columnCell]对应数据的行列坐标。
  /// [isLongPress]表示被拆分单元格此时是否触发了长按。当此单元格拦截了[GestureLongPressHandler]定义的相关事件时，
  /// 如果希望[KqTable]还能处理拖拽改变行高和列宽，则需要外部获取[gestureLongPressHandler]调用相关事件方法。
  /// 子单元格如果需要长按事件，需要主动实现长按监听。
  /// [child]为子单元格数据内容
  Widget buildChildCell(BuildContext context, int row, int column,
      bool isLongPress, SplitCell child);
}

/// 定义被拆分单元格
class SplitCell {
  const SplitCell(
      {this.children, this.value, this.flex = 1, this.axis = Axis.vertical})
      : assert(flex == null || flex >= 0);

  /// 定义子单元格数据，当此值不为空时，此单元格不会绘制到界面，而是绘制子单元格
  final List<SplitCell>? children;

  /// 当前单元格占比，不传则大小根据单元格内容自适应
  final int? flex;

  /// 子单元格排列方向
  final Axis axis;

  /// 当[children]为空时，当前单元格绘制的内容
  final dynamic value;
}
